package com.b2c.erp.controller.api;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.b2c.erp.DataConfigObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

public class AuthInterceptor implements HandlerInterceptor {
    private static Logger log = LoggerFactory.getLogger(AuthInterceptor.class);
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        if(StringUtils.isEmpty(response.getHeader("Access-Control-Allow-Origin")))response.addHeader("Access-Control-Allow-Origin", "http://192.168.0.110:8080");
        if(StringUtils.isEmpty(response.getHeader("Access-Control-Allow-Credentials")))response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");//服务器支持的所有头信息字段
        response.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
        response.addHeader("Access-Control-Max-Age", "3600");//请求的有效期，单位为秒
        response.addHeader("XDomainRequestAllowed", "1");
        log.info("访问请求拦截:" + request.getRequestURL().toString());

        String secret = DataConfigObject.getInstance().getJwtSecret();
        Algorithm algorithm = Algorithm.HMAC256(secret);
        try {
            String token = request.getHeader("Authorization");
            if(StringUtils.hasText(token)==false){
                returnJson(response, "{\"code\":601,\"msg\":\"未授权\"}");
                return false;
            }
            token = token.replace("Bearer","").trim();
            JWTVerifier verifier = JWT.require(algorithm).withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);

            Integer userId = jwt.getClaim("userId").asInt();
            DataConfigObject.getInstance().setLoginUserId(userId);
        }catch (TokenExpiredException e){
            returnJson(response, "{\"code\":602,\"msg\":\"授权过期\"}");
            return false;
        }
        return true;
    }

    public List<String> noneRoleList(){
        return Arrays.asList("manage_check_user_login","bb","cc");
    }
    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
